package com.yupi.springbootinit.ws;

import com.yupi.springbootinit.config.GetHttpSessionConfigurator;
import com.yupi.springbootinit.config.WebSocketConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@ServerEndpoint(value = "/webSocketToUser/{id}",configurator = GetHttpSessionConfigurator.class)
public class WebSocketToUser {
    private static ConcurrentHashMap<String,WebSocketToUser> webSocketSet=new ConcurrentHashMap<>();

    private static Session session;

    private static String sid="";

    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session, EndpointConfig config){
        String httpSessionId=(String) config.getUserProperties().get("sessionId");
        this.session=session;
        this.sid=id;
        webSocketSet.put(sid,this);
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + message);
    }

    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }

    public boolean sendToUser(String message,String sendUserId) throws IOException {
        if (webSocketSet.get(sendUserId) != null) {
            if (!sid.equals(sendUserId)) {
                return false;
            } else {
                webSocketSet.get(sendUserId).sendMessage(message);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    log.error("失败了");
                    e.printStackTrace();
                }
                return true;
            }

        } else {
            return false;
        }
    }
}
